<template>
  <div>
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>promotion management</el-breadcrumb-item>
      <el-breadcrumb-item>promotion list</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区-->
    <el-card>
      <!--template #header>
        <div class="card-header">
          <span>Card name</span>
          <el-button class="button" text>Operation button</el-button>
        </div>
      </template>-->

      <!--搜索与添加-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <template #append>
              <el-button @click="getUserList">
                <el-icon>
                  <Search/>
                </el-icon>
              </el-button>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!--用户列表区域-->
      <el-table :data="userlist" style="width: 100%" stripe border>
        <el-table-column type="index" label="#"/>
        <el-table-column prop="username" label="姓名"/>
        <el-table-column prop="mobile" label="电话"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="role_name" label="角色"/>
        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!--作用域插槽-->
          <template v-slot="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="showEditDialog(scope.row)"/>
            <el-button type="danger" :icon="Delete" size="small" @click="removeUserById(scope.row.id)"/>

            <el-tooltip
              effect="dark"
              content="分配橘色"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" :icon="Setting" size="small"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:currentPage="queryInfo.pagenum"
        v-model:page-size="queryInfo.pagesize"
        :page-sizes="[1, 2, 5, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!--对话框-->
    <el-dialog
      v-model="dialogVisible"
      title="添加用户"
      width="50%"
      @close="addDialogClosed"
    >
      <!--内容主题区域-->

      <el-form
        ref="ruleFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="70px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"/>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addUser"
        >Confirm</el-button
        >
      </span>
      </template>
    </el-dialog>

    <!--修改用户的对话框-->
    <el-dialog
      v-model="editDialogVisable"
      title="修改用户"
      width="50%"
      @close="getUserList"
    >
      <el-form
        ref="editFormRef"
        :rules="addFormRules"
        :model="editForm"
        label-width="70px"
        status-icon
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"/>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="editDialogVisable = false">Cancel</el-button>
        <el-button type="primary" @click="editUserInfo"
        >Confirm</el-button
        >
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ElementPlus, Search, Delete, Edit, Setting } from '@element-plus/icons-vue'
</script>

<script>
  export default {
    name: 'Users',
    data () {
      // 验证规则
      var checkEmail = (rule, value, cb) => {
        const regEmail = /^\w+@\w+(\.\w+)+$/
        if (regEmail.test(value)) {
          return cb()
        }

        cb(new Error('请输入合法邮箱'))
      }

      var checkMobile = (rule, value, cb) => {
        const regMobile = /^1[34578]\d{9}$/
        if (regMobile.test(value)) {
          return cb()
        }
        //返回一个错误提示
        cb(new Error('请输入合法的手机号码'))
      }

      return {
        // 获取用户列表参数的对象
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 2,
        },
        userlist: [],
        total: 0,
        // 控制对话框的显示
        dialogVisible: false,
        // 添加用户表单数据
        addForm: {
          username: '',
          password: '',
          email: '',
          mobile: '',
        },
        // 表单规则
        addFormRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
          ],
          password: { required: true, message: '请输入密码', trigger: 'blur' },
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur' },
          ],
          mobile: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { validator: checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur' },
          ],
        },

        // 控制修改用户对话框的显示
        editDialogVisable: false,

        editForm: {},
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      // 获取用户列表的数据
      async getUserList () {
        const { data: res } = await this.$http.get('users', { params: this.queryInfo })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.userlist = res.data.users
        this.total = res.data.total
      },
      // 监听pageSize的时间
      handleSizeChange (newSize) {
        // console.log(newSize)
        this.queryInfo.pagesize = newSize
        this.getUserList()
      },
      // 监听页码值改变事件
      handleCurrentChange (newPage) {
        // console.log(newPage)
        this.queryInfo.pagenum = newPage
        this.getUserList()
      },
      // 监听switch开关状态的改变
      async userStateChanged (row) {
        // console.log(row)
        let { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
        if (res.meta.status !== 200) {
          row.mg_state = !row.mg_state
          return this.$message.error('更新用户数据失败！')
        }
        this.$message.success('更新用户状态成功！')
      },
      // 监听添加用户对话框的关闭事件
      addDialogClosed () {
        this.$refs.ruleFormRef.resetFields()
        // this.addForm = {}
      },
      // 点击按钮，新增用户
      addUser () {
        this.$refs.ruleFormRef.validate(async isValid => {
          // console.log(isValid)
          if (isValid) {
            let { data: res } = await this.$http.post('users', this.addForm)
            if (res.meta.status !== 201) { this.$message.error('添加用户失败') }
            this.$message.success('成功添加')
            this.dialogVisible = false
            await this.getUserList()
          }

        })
      },
      // 显示编辑用户的对话框
      showEditDialog (row) {
        this.editDialogVisable = true
        // console.log(row)
        this.editForm = row
      },
      // 修改用户信息并提交
      editUserInfo () {
        this.$refs.editFormRef.validate(async valid => {
          if (valid) {
            let { data: res } = await this.$http.put('users/' + this.editForm.id,
              {
                email: this.editForm.email,
                mobile: this.editForm.mobile,
              })

            if (res.meta.status !== 200) {
              return this.$message.error('更新用户失败')
            }
            this.editDialogVisable = false
            await this.getUserList()
            this.$message.success('更新成功！')
          }
        })
      },
      // 根据id删除用户
      removeUserById (id) {
        this.$confirm(
          '此操作将永久删除该用户，是否继续？', '提示', {
            confirmButtonText: 'OK',
            cancelButtonText: '取消',
            type: 'warning',
          },
        ).then(
          () => {
            this.$http.delete('users/'+id).then((res)=>{
              // console.log(res)
              if (res.data.meta.status !== 200) {
                return this.$message.error(res.data.meta.msg)
              }
            })
            this.$message.success('删除成功')
          },
        ).catch(
          () => {
            this.$message.info('取消删除！')
          },
        )
      },
    },
  }
</script>

<style lang="less" scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .box-card {
    width: 480px;
  }

  .el-table {
    margin-top: 15px;
    font-size: 12px;
  }

  .el-pagination {
    margin-top: 15px;
  }

</style>